package myJs.implicits

import cats.effect.unsafe.implicits.global
import cats.effect.{IO, SyncIO}
import myJs.Implicits.MyPen
import myJs.myPkg.topology.{Line, Pen, Topology, TopologyNode}
import org.scalajs.dom.{DragEvent, Event}

import scala.scalajs.js
import scala.scalajs.js.|

/** Created by Administrator on 2020/1/16
  */
trait MyTopologyTool {

  type MyPen = Pen | js.Array[Pen]

  type MyLine = Line | js.Array[Line]

  implicit class MyPenOp(myPen: MyPen) {

    def toPens: js.Array[Pen] = {
      if (myPen.isInstanceOf[Pen]) {
        js.Array(myPen.asInstanceOf[Pen])
      } else {
        myPen.asInstanceOf[js.Array[Pen]]
      }
    }

    def toPen: Pen = {
      myPen.toPens.head
    }

  }

  implicit class PenOp(pen: Pen) {

    def toLine: Line = {
      pen.asInstanceOf[Line]
    }

    def toNode = {
      pen.asInstanceOf[TopologyNode]
    }

  }

  implicit class MyLineOp(myLine: MyLine) {

    def toLines: js.Array[Line] = {
      if (myLine.isInstanceOf[Line]) {
        js.Array(myLine.asInstanceOf[Line])
      } else {
        myLine.asInstanceOf[js.Array[Line]]
      }
    }

  }

  implicit class MyTopology(v: Topology) {

    def myOn(events: String, handler: js.Function1[MyPen, SyncIO[Unit]]) = {
      val useHandler = (v: MyPen) => handler(v).unsafeRunSync()
      v.on(events, useHandler)
    }

    def myOn(events: String, handler: SyncIO[Unit]) = {
      val useHandler = () => handler.unsafeRunSync()
      v.on(events, useHandler)
    }

    def myOnAsync(events: String, handler: js.Function1[MyPen, IO[Unit]]) = {
      val useHandler = (v: MyPen) => handler(v).unsafeRunAndForget()
      v.on(events, useHandler)
    }

  }

}
